package zhuzx.solution;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

/**
 * 替换sql中tags_time的值（格式化）
 * @author zhuzx 2018年10月18日
 */
public class ReplaceTagsTime {
	
	public static void main(String[] args) throws Exception {
//		String s = "aaa-a";
//		System.out.println(s.lastIndexOf('-', 2));
//		System.out.println(s.lastIndexOf('-', 4));
//		testReplaceTagsTimeForBigFile();
		
		replaceTagsTime();
	}

	public static void testReplaceTagsTimeForBigFile() throws IOException {
		List<String> list = getAllLine();
		int multiplier = 40;
		List<String> bigList = new ArrayList<>(list.size() * multiplier);
		for (int i=0; i<multiplier; i++) {
			bigList.addAll(list);
		}
		replaceTagsTime(bigList);
		System.out.println("尝试读入刚才生成的大文件");
		List<String> resultList = Files.readAllLines(
				Paths.get("C:/Users/zxzhu.abcft/Desktop/replacedNewSql.sql"));
		System.out.println("大文件读入成功：" + resultList.size() + "行");
	}
	
	public static void replaceTagsTime() throws IOException {
		replaceTagsTime(getAllLine());
	}
	
	private static List<String> getAllLine() throws IOException {
		String file = "C:\\Users\\zxzhu.abcft\\Desktop\\report_info_rollback.sql";
		System.out.println("开始读取sql文件：" + file);
		List<String> list = Files.readAllLines(Paths.get(file));
		return list;
	}
	
	private static void replaceTagsTime(List<String> list) throws IOException {
		System.out.println("开始处理sql文本，共" + list.size() + "行");
		String key = "`tags_time`='";//update和delete可以全部匹配到
		int keyOffset = key.length();
		int loopCount = 6;//insert语句的右数第n个逗号右边即为tags_time
		for (int i=0; i<list.size(); i++) {
			String str = list.get(i);
			StringBuilder sql = new StringBuilder(str);
			if (str.startsWith("INSERT")) {
				int start = str.length();
				for (int j=1; j<=loopCount; j++) {
					start = str.lastIndexOf(',', start-1);
				}
				format(sql, start, 3, i);//找到tags_time前面的逗号位置，", '".length() == 3
			} else {
				int start = sql.indexOf(key);
				format(sql, start, keyOffset, i);
				if (str.startsWith("UPDATE")) {
					start = sql.indexOf(key, start+1);
					format(sql, start, keyOffset, i);
				} else if (!str.startsWith("DELETE")) {
					throw new RuntimeException("预期外的语句（非法的开头），行号" + (i+1));
				}
			}
			list.set(i, sql.toString());
		}
		Path newFile = Paths.get("C:/Users/zxzhu.abcft/Desktop/replacedNewSql.sql");
		Files.deleteIfExists(newFile);
		Files.createFile(newFile);
		System.out.println("替换完毕，开始写入新文件：" + newFile.toUri());
		Files.write(newFile, list, StandardOpenOption.APPEND);
		System.out.println("处理完毕");
	}
	
	private static void format(StringBuilder sql, int start, int keyOffset, int index) {
		start += keyOffset + 19;
		int end = sql.indexOf("'", start);
		String dec = sql.substring(start, end);
		if (dec.length() == 0) {
			sql.insert(start, ".000");
		} else if (dec.length() == 7) {
			sql.delete(start+1, start+4);
		} else {
			throw new RuntimeException("预期外的时间格式" + dec + "，第" + (index+1) + "行");
		}
	}
	
}